package com.xiewz.executor;

import com.xiewz.util.WeiBoUtil;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.Objects;

/**
 * 上传图片到微博图床
 * 得到新的Markdown图片路径
 */
public class WeiBoExecutor implements Executor {
    private String mdFilePath;

    public WeiBoExecutor(String mdFilePath) {
        this.mdFilePath = mdFilePath;
    }

    @Override
    public Object doExecutor(String content) {
        return uploadImg(content);
    }

    /**
     * 上传文件到微博图床并返回md地址
     * @param filepath
     * @return
     */
    private String uploadImg(String filepath) {
        String url = "https://picupload.weibo.com/interface/pic_upload.php?ori=1&mime=image%2Fjpeg&data=base64&url=0&markpos=1&logo=&nick=0&marks=1&app=miniblog";
        if (filepath == null || "".equals(filepath.trim()) || filepath.startsWith("http")) {
            System.out.println("跳过图片：--"+filepath);
            return null;
        }

        String[] split = filepath.split("/|\\\\");
        String fileName = split[split.length - 1];

        // 相对路径转换为绝对路径
        if (!filepath.startsWith(mdFilePath.substring(0, 3))) {
            int lastIndexOf = mdFilePath.lastIndexOf("\\");
            String prePath = mdFilePath.substring(0, lastIndexOf + 1);
            filepath = prePath + filepath;
        }

        String base = ImageToBase64(filepath);
        // 上传到微博图床
        String result = WeiBoUtil.sendPostBase64(url, base);

        // 转成Markdown格式图片
        String markdownImg = WeiBoUtil.parseMarkdownImg(result, fileName);
        return markdownImg;
    }

    /**
     * 本地图片转换Base64的方法
     *
     * @param imgPath
     */

    public String ImageToBase64(String imgPath) {
        byte[] data = null;
        String str = null;
        // 读取图片字节数组
        try {

            data = Files.readAllBytes(Paths.get(imgPath));
            // 返回Base64编码过的字节数组字符串
            Base64.Encoder encoder = Base64.getEncoder();
            byte[] encode = encoder.encode(Objects.requireNonNull(data));
            str = new String(encode, "UTF-8");
            System.out.println("本地图片转换Base64:" + str);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {

        }
        // 对字节数组Base64编码
        return str;
    }
}
